package com.heima.kafka.sample;

import org.apache.kafka.clients.producer.*;

import java.util.Properties;
import java.util.concurrent.ExecutionException;

/**
 * 生产者
 */
public class ProducerQuickStart {

    public static void main(String[] args) {
        Properties properties = new Properties();
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.200.130:9092");
        properties.put(ProducerConfig.RETRIES_CONFIG,5);
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.ACKS_CONFIG,"all");
        properties.put(ProducerConfig.COMPRESSION_TYPE_CONFIG,"gzip");


        // 获取生产者核心对象
        KafkaProducer<String, String> producer = new KafkaProducer<>(properties);

        //同步发送

       /* for (int i =0;i<100;i++) {
            // 封装消息
            ProducerRecord<String, String> producerRecord = new ProducerRecord<String, String>("topic","你好","kafka"+i);
            try {
                RecordMetadata metadata = producer.send(producerRecord).get();
                System.out.println(metadata.offset());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }*/
        for (int i = 0; i <100; i++) {

            //异步发送
            ProducerRecord<String, String> producerRecord = new ProducerRecord<>("topic", "你好", "kafka" + i);
            producer.send(producerRecord, new Callback() {
                @Override
                public void onCompletion(RecordMetadata recordMetadata, Exception e) {
                    if (e!=null){
                        System.out.println("记录异常信息到日志表中");
                    }
                    System.out.println(recordMetadata.offset());
                }
            });
        }

        producer.close();

    }

}